import commonStore from "../store/commonStore"
import config from "./config"
import { editLoadingNum, getStorage, setStorage, showToast } from "./util"
export interface ResData<T> {
	code : number
	data : T
	message : string
}
let APIJUMPLOGIN = false
export const request = <T = any>(options : any, header ?: { token : string }, url ?: string) => {
	return new Promise<T>((resolve, reject) => {
		let userAuth = getStorage('userAuth') || {}
		uni.request({
			url: url?url:config.apiUrl + options.url,
			method: options.method || 'GET',
			data: options.data || {},
			header: header ? header : {
				//Authorization: 'Bearer '+ (userAuth.token ? userAuth.token : ''),
				token:userAuth.token ? userAuth.token : ''
			},
			success: (res : any) => {
				if (res.data.code === 401||res.data.code === 105) {
					editLoadingNum()
					// 登录过期
					if (APIJUMPLOGIN === false) {
						APIJUMPLOGIN = true
						showToast('登录已过期', {}, () => {
							setStorage("userAuth", '');
							commonStore.commit('addReload', 'userIndex')
							commonStore.commit('addReload', 'index')
							uni.redirectTo({
								url: '/pages/index/index'
							})
							setTimeout(()=>{
								APIJUMPLOGIN=false
							},2000)
						})
					}
					reject(res)
					return
				} else if (res.data.code !== 200) {
					let str=res.data.msg
					editLoadingNum()
					setTimeout(()=>{
						uni.showToast({
							'title': str||'请求接口失败',
							'duration': 2000,
							'icon': 'none'
						})
					},300)
					
					reject(res)
					return
				}
				resolve(res.data)
			},
			fail: (err) => {
				editLoadingNum()
				uni.showToast({
					'title': '请求接口失败',
					'duration': 2000,
					'icon': 'none'
				})
				reject(err)
			}
		})
	})
}